package com.xhb.campusservices.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhb.campusservices.common.lang.Result;
import com.xhb.campusservices.pojo.User;
import com.xhb.campusservices.service.UserService;
import com.xhb.campusservices.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    JWTUtils jwtUtils;

    @Value("${upload.dir}")
    private String realPath;


    /**
     * 查询用户信息
     *
     * @return
     */
    @GetMapping("/list")
    public Result list(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userId = jwtUtils.getUserId(token);
        //获取是否为管理员，是的话，查询所有用户信息
        if (userId.equals("8")) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.ne(User::getId, userId);
            List<User> list = userService.list(queryWrapper);
            return Result.succ(200, "查询成功", list);
        } else {
            //不然，只查询当前用户的信息
            User byId = userService.getById(userId);
            return Result.succ(200, "查询成功", byId);
        }
    }


    /**
     * 修改用户信息
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/userEdit")
    public Result edit(@Validated @RequestBody User user, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(user.getId()).equals(jwtUtils.getUserId(token))) {
            userService.updateById(user);
        } else {
            return Result.fail(403, "没有修改权限!");
        }
        //修改成功
        return Result.succ(200, "修改成功", null);
    }

    /**
     * 修改用户头像
     *
     * @param photo
     * @param id
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/modifyPhoto/{id}")
    public Result upload(@RequestPart("photo") MultipartFile photo, @PathVariable(name = "id") Long id, HttpServletRequest request) throws IOException {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(id).equals(jwtUtils.getUserId(token))) {
            log.info("上传的信息：headerImg={}", photo.getSize());
            if (!photo.isEmpty()) {
                //获取新头像文件名
                String filename = photo.getOriginalFilename();
                //判断文件类型
                String allowType = "gif,jpg,png,jpeg";
                //文件非空
                if (!("").equals(filename.trim()) && filename.length() > 0) {
                    String ex = (String) filename.subSequence(filename.lastIndexOf(".") + 1,
                            filename.length());
                    if (allowType.indexOf(ex.toLowerCase()) < 0) {
                        return Result.fail("文件类型不对~只支持(gif,jpg,png,jpeg)");
                    }
                    User user = userService.getById(id);
                    String newFileName = user.getPhoto();

                    //头像大小超过1M的就压缩，不然不压缩
                    if(photo.getSize()>1000000){
                        //压缩图片大小
                        BufferedImage finalImage = reduce(ImageIO.read(photo.getInputStream()),0.5f);
                        //图片输出路径，以及图片名
                        FileOutputStream fileOutputStream = new FileOutputStream(realPath+newFileName);
                        ImageIO.write(finalImage,"jpg",fileOutputStream);
                        fileOutputStream.close();
                    }else{
                        photo.transferTo(new File(realPath + newFileName));
                    }
                    return Result.succ(200,"头像修改成功",null);
                }
                return Result.fail("文件为空~");
            }
            return Result.fail("头像未上传~");
        }
        return Result.fail(403, "没有修改权限!");
    }


    /**
     * 注销用户信息(只能删除自己的账号)
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/userDel/{id}")
    public Result del(@PathVariable(name = "id") Long id, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(id).equals(jwtUtils.getUserId(token))) {
            userService.removeById(id);
        } else {
            return Result.fail(403, "没有删除权限!");
        }
        //注销成功
        return Result.succ(200, "注销成功", null);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        //获取还未过期的token
        String token = request.getHeader("Authorization");
        //刷新token时间为0
        String newToken = jwtUtils.delToken(token);
        response.setHeader("Authorization", newToken);
        SecurityUtils.getSubject().logout();
        return Result.succ(200, "退出成功", null, newToken);
    }


    /**
     * 压缩图片的方法
     * @param read  图片所在路径
     * @param scale  通过比例压缩
     * @return
     */
    public BufferedImage reduce(BufferedImage read,float scale){
        //压缩之后的长度和宽度
        int height = (int) (scale * read.getHeight());
        int width = (int) (scale * read.getWidth());
        BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        finalImage.getGraphics().drawImage(read.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        return finalImage;
    }


}
